<?php
//Cache file
class Cache
{
    var $cache_dir = './cache/';    
    var $caching = false;
    var $file = '';
    function cacheFile($name)
    {
        $this->file = $this->cache_dir .'file/'. $name;		
        if ( file_exists ( $this->file ))
        {
            $handle = fopen( $this->file , "r");
            do {
                $data = fread($handle, filesize($this->file));
                if (strlen($data) == 0) {
                    break;
                }
                return $data;
            } while (true);
            fclose($handle);			
            exit();			
        }
        else
        {
            $this->caching = true;
            ob_start();
			
        }
    }
   
    function closeFile($data)
    {
		$dlieu = $data;
        if ( $this->caching )
        {
            $data = ob_get_clean();           
            $fp = fopen( $this->file , 'w' );
            fwrite ( $fp , $dlieu );
            fclose ( $fp );
        }
    }

function CacheArray($name,$array)// Xuất file cachesql
	{
		
		$file = $this->cache_dir.'sql/'.$name.'.txt';
		
		if (file_exists($file)) {
			$records = unserialize(file_get_contents($file));
		} else {
			$OUTPUT = serialize($array);
			$fp = fopen($file,"w");
			fputs($fp, $OUTPUT);
			fclose($fp);
		} // end else
		return $records;
	}
	
//#Cache file
function CacheSql($name,$sql)// Xuất file cachesql
	{
		$query = $sql;
		$file = $this->cache_dir.'sql/'.$name.'.txt';
		
		if (file_exists($file)) {
			$records = unserialize(file_get_contents($file));
		} else {		
			$result = MySQL_query($query)
				or die (MySQL_error());
			while ($record = MySQL_fetch_array($result) ) {
				$records[] = $record;
			}
			$OUTPUT = serialize($records);
			$fp = fopen($file,"w");
			fputs($fp, $OUTPUT);
			fclose($fp);
		} // end else
		return $records;
	}
//#Cache SQL
}
?>